package com.xiaoniu.forum.config;

import com.xiaoniu.forum.common.constant.RedisKeyConstant;
import com.xiaoniu.forum.common.utils.CountUtils;
import com.xiaoniu.forum.entity.CommunityTopicEntity;
import com.xiaoniu.forum.service.CommunityTopicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Configuration
@EnableScheduling
@Slf4j
public class ForumScheduleConfig {

    @Autowired
    private CountUtils countUtils;

    @Autowired
    private CommunityTopicService communityTopicService;

    /**
     * 每一分钟执行 将话题查看数更新
     */
    @Scheduled(cron = "0 */1 * * * ?")
    private void saveTopicViewCountTasks() {
        long begin = System.currentTimeMillis();
        log.info("开始执行更新话题查看数的定时任务");
        try {
            Map<Object, Object> map = countUtils.getAllHashByKey(RedisKeyConstant.SCHEDULING_VIEW_COUNT_KEY);
            if (map.isEmpty()) {
                log.info("无用户游览话题,退出定时任务");
                return;
            }
            Set<Object> keys = map.keySet();
            HashSet<String> topicIds = new HashSet<>();
            //转换泛型
            keys.forEach(k -> {
                topicIds.add((String) k);
            });
            //查询
            List<CommunityTopicEntity> communityTopicEntityList = communityTopicService.listByIds(topicIds);

            communityTopicEntityList.forEach(communityTopicEntity -> {
                Integer viewCount = Integer.parseInt((String) map.get(communityTopicEntity.getId()));
                communityTopicEntity.setViewCount(viewCount + communityTopicEntity.getViewCount());
            });

            //批量更新
            communityTopicService.updateTopicBatchById(communityTopicEntityList);

        } catch (Exception e) {
            log.error("执行更新话题查看数的任务失败了,原因是:{}", e.getMessage());
            e.printStackTrace();
        } finally {
            countUtils.flush(RedisKeyConstant.SCHEDULING_VIEW_COUNT_KEY);
            long end = System.currentTimeMillis();
            log.info("执行更新话题查看数任务耗时:{}ms",end-begin);
        }

    }
}
